﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using dotNails.CodeGen.Models.dotNails;

namespace dotNails.CodeGen.Models {
	/// <summary>
	/// Summary description for TemplatedFile.
	/// </summary>
	public class TemplatedFile : ITemplatedFile {
		private List<CodeBlock> _codeBlocks = new List<CodeBlock>();

		#region Properties
		/// <summary>
		/// Just the filename
		/// </summary>
		private string _filename = "";
		public string FileName {
			get { return _filename; }
			set { _filename = value; }
		}
		
		private FileTypeEnum _fileType;
		public FileTypeEnum FileType {
			get { return _fileType; }
			set { _fileType = value; }
		}
		
		public List<CodeBlock> CodeBlocks {
			get {return _codeBlocks;}
		}

		private string _projectName = string.Empty;
		public string ProjectName {
			get { return _projectName; }
		}

		/// <summary>
		/// Full path to destination.  This is used for writing the file for the first time (no working directory is used in this iteration)
		/// </summary>
		private string _fullDestinationFolder;
		public string FullDestinationFolder {
			get { return _fullDestinationFolder; }
		}

		/// <summary>
		/// Relative path to destination.  This class creates the file directly in its destination (no working directory is used in this iteration)
		/// </summary>
		private string _relativeDestinationFolder;
		public string RelativeDestinationFolder {
			get { return _relativeDestinationFolder; }
		}

		public string FullDestinationFilePath {
			get { return Path.Combine(_fullDestinationFolder, _filename); }
		}
		#endregion Properties

		public TemplatedFile(FileTypeEnum fileType, string fullDestinationFolder, string relativeDestinationFolder, string projectName) {
			FileType = fileType;
			_fullDestinationFolder = fullDestinationFolder;
			_relativeDestinationFolder = relativeDestinationFolder;
			_projectName = projectName;
		}

		public void GenerateFile() {
			StringBuilder output = new StringBuilder();			
			bool fileDoesNotExist = !File.Exists(this.FullDestinationFilePath);
			
			// Never overwrite an existing file
			if (fileDoesNotExist) {
				// Currently doesn't implement concept of placing CodeBlocks within regions.  It just appends them in order.
				for (int i = 0; i < _codeBlocks.Count; i++) {
					output.Append(_codeBlocks[i].Render());
				}

				if (!Directory.Exists(this.FullDestinationFolder)) {
					System.IO.Directory.CreateDirectory(this.FullDestinationFolder);
				}

				using (StreamWriter sw = new StreamWriter(this.FullDestinationFilePath, false)) {
					sw.Write(output.ToString());
					sw.Flush();
					sw.Close();
				}
			}
		}
		
	}
}
